﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAKS.IServices;
using SAKS.Models;
using SAKS.Services.Query;
using SAKS.ViewModels;
using NHibernate.Linq;
using NHibernate;

namespace SAKS.Services
{
    public class PersonServices : ServicesBase<PersonInfo>,IPersonServices
    {
        public override void Update(PersonInfo info)
        {
            var ori = Session.Get<PersonInfo>(info.Id);
            info.Version = ori.Version;
            Session.Merge(info);
        }

        public override object[] List(int first, int pageSize, out int? totalRecords, string key)
        {
            var query = new PagedPersonInfoSearch(Session) { First = first, PageSize = pageSize, Key = key };
            var result = query.Execute();
            totalRecords = result.TotalItems;
            var ret = from a in result.PageOfResults
                      select new string[]{
                          a.Id.ToString(),
                          a.Name,
                          a.Gender.ToString(),
                          a.BirthDay.Value.Year + "-" + a.BirthDay.Value.Month,
                          a.TechnicalTitle,
                          a.HighestDegree,
                          a.Major,
                          a.Occupation,
                          a.UserName
                      };
            return ret.ToArray();
        }

        public object[] GetPersonInfoByRealName(string realname)
        {
            if (String.IsNullOrEmpty(realname)) throw new ArgumentException("username 不可以为空或null");
            var list = Session.QueryOver<PersonInfo>().Where(p => p.Name == realname).List();
            var query = from p in list
                        where p.Name == realname
                        select new PersonInfoCreateUpdateModel
                        {
                            Name = p.Name,
                            Gender = p.Gender.ToString(),
                            BirthDay = p.BirthDay.Value.ToString("yyyy-MM-dd"),
                            HighestDegree = p.HighestDegree,
                            Major = p.Major,
                            Occupation = p.Occupation,
                            TechnicalTitle = p.TechnicalTitle
                        };
            return query.ToArray();
        }
    }
}
